package com.yuanqiao.insight.modules.grok.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqiao.insight.common.util.common.RedisUtils;
import com.yuanqiao.insight.modules.grok.entity.UtlGrok;
import com.yuanqiao.insight.modules.grok.entity.UtlGrokFormula;
import com.yuanqiao.insight.modules.grok.service.IUtlGrokFormulaService;
import com.yuanqiao.insight.modules.grok.service.IUtlGrokService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.constant.CacheConstant;
import com.insight.common.system.query.QueryGenerator;
import com.yuanqiao.insight.acore.system.entity.SysDict;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description: grok表达式
 * @Author: jeecg-boot
 * @Date: 2024-02-19
 * @Version: V1.0
 */
@Api(tags = "grok表达式")
@RestController
@RequestMapping("/grok")
@Slf4j
public class UtlGrokController {
    @Autowired
    private IUtlGrokService utlGrokService;
    @Autowired
    private IUtlGrokFormulaService utlGrokFormulaService;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 分页列表查询
     *
     * @param utlGrok
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "grok表达式-分页列表查询")
    @ApiOperation(value = "grok表达式-分页列表查询", notes = "grok表达式-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(UtlGrok utlGrok,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        final String grokName = utlGrok.getGrokName();
        final String grokCode = utlGrok.getGrokCode();
        utlGrok.setGrokName("");
        utlGrok.setGrokCode("");
        QueryWrapper<UtlGrok> queryWrapper = QueryGenerator.initQueryWrapper(utlGrok, req.getParameterMap());
        queryWrapper.like(StringUtils.isNotBlank(grokName), "grok_name", grokName)
                .like(StringUtils.isNotBlank(grokCode), "grok_code", grokCode);

        Page<UtlGrok> page = new Page<UtlGrok>(pageNo, pageSize);
        IPage<UtlGrok> pageList = utlGrokService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param utlGrok
     * @return
     */
    @AutoLog(value = "grok表达式-添加")
    @ApiOperation(value = "grok表达式-添加", notes = "grok表达式-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody UtlGrok utlGrok) {
        final int count = utlGrokService.count(new LambdaQueryWrapper<UtlGrok>()
                .eq(UtlGrok::getGrokCode, utlGrok.getGrokCode()));
        if (count > 0) {
            return Result.OK().error500("grok标识已存在");
        }
        utlGrokService.save(utlGrok);
        return Result.OK("添加成功!");
    }

    /**
     * 编辑
     *
     * @param utlGrok
     * @return
     */
    @AutoLog(value = "grok表达式-编辑")
    @ApiOperation(value = "grok表达式-编辑", notes = "grok表达式-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody UtlGrok utlGrok) {
        final int count = utlGrokService.count(new LambdaQueryWrapper<UtlGrok>()
                .ne(UtlGrok::getId, utlGrok.getId())
                .eq(UtlGrok::getGrokCode, utlGrok.getGrokCode()));
        if (count > 0) {
            return Result.OK().error500("grok标识已存在");
        }
        utlGrokService.updateById(utlGrok);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "grok表达式-通过id删除")
    @ApiOperation(value = "grok表达式-通过id删除", notes = "grok表达式-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        utlGrokService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "grok表达式-批量删除")
    @ApiOperation(value = "grok表达式-批量删除", notes = "grok表达式-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids") String ids) {
        this.utlGrokService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "grok表达式-通过id查询")
    @ApiOperation(value = "grok表达式-通过id查询", notes = "grok表达式-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id") String id) {
        UtlGrok utlGrok = utlGrokService.getById(id);
        return Result.OK(utlGrok);
    }

    /**
     * 通过id查询
     *
     * @param grokId
     * @return
     */
    @AutoLog(value = "grok表达式-通过主表ID查询")
    @ApiOperation(value = "grok表达式-通过主表ID查询", notes = "grok表达式-通过主表ID查询")
    @GetMapping(value = "/queryUtlGrokFormula")
    public Result<?> queryUtlGrokFormula(@RequestParam(name = "grokId") String grokId) {
        List<UtlGrokFormula> utlGrokFormulaList = utlGrokFormulaService.list(new LambdaQueryWrapper<UtlGrokFormula>()
                .eq(UtlGrokFormula::getGrokId, grokId)
                .eq(UtlGrokFormula::getDelFlag, "0")
                .orderByDesc(UtlGrokFormula::getCreateTime));
        return Result.OK(utlGrokFormulaList);
    }

    /**
     * grok表达式-添加表达式
     *
     * @param utlGrokFormula
     * @return
     */
    @AutoLog(value = "grok表达式-添加表达式")
    @ApiOperation(value = "grok表达式-添加表达式", notes = "grok表达式-添加表达式")
    @PostMapping(value = "/addUtlGrokFormula")
    public Result<?> addUtlGrokFormula(@RequestBody UtlGrokFormula utlGrokFormula) {
        utlGrokFormula.setDelFlag("0");
        utlGrokFormulaService.add(utlGrokFormula);
        return Result.OK("添加成功");
    }

    /**
     * grok表达式-编辑表达式
     *
     * @param utlGrokFormula
     * @return
     */
    @AutoLog(value = "grok表达式-编辑表达式")
    @ApiOperation(value = "grok表达式-编辑表达式", notes = "grok表达式-编辑表达式")
    @PutMapping(value = "/editUtlGrokFormula")
    public Result<?> editUtlGrokFormula(@RequestBody UtlGrokFormula utlGrokFormula) {
        utlGrokFormulaService.modify(utlGrokFormula);
        return Result.OK("添加成功");
    }

    /**
     * grok表达式-删除表达式
     *
     * @param id
     * @return
     */
    @AutoLog(value = "grok表达式-删除表达式")
    @ApiOperation(value = "grok表达式-删除表达式", notes = "grok表达式-删除表达式")
    @DeleteMapping(value = "/delUtlGrokFormula")
    public Result<?> delUtlGrokFormula(String id) {
        utlGrokFormulaService.delete(id);
        return Result.OK("添加成功");
    }

    @AutoLog(value = "grok表达式-刷新缓存")
    @RequestMapping(value = "/refreshCache")
    public Result<?> refreshCache() {
        Result<?> result = new Result<SysDict>();
        //清空字典缓存
        Set<String> keys = redisUtils.keys(CacheConstant.SYS_GROK_CACHE + "*");
        redisUtils.del(keys);
        //重载缓存
        final List<UtlGrokFormula> list = utlGrokFormulaService.list();
        list.stream().collect(Collectors.groupingBy(UtlGrokFormula::getGrokCode))
                .forEach((key, value) -> {
                    String cKey = String.format("%s:%s", CacheConstant.SYS_GROK_CACHE, key);
                    Map<String, Object> map = value
                            .stream()
                            .collect(Collectors.toMap(UtlGrokFormula::getId, UtlGrokFormula::getGrokFormula));
                    redisUtils.hmset(cKey, map);
                });
        return result;
    }
}
